import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:yh_core_flutter_project/project/common/managers/user_manager.dart';
import 'package:yh_core_flutter_project/project/config/app_env_config.dart';
import 'package:yh_core_flutter_project/project/modules/login/models/user_model/user_model.dart';
import 'package:yh_core_flutter_project/project/modules/login/models/user_model/version_model.dart';
import 'package:yh_core_flutter_project/project/common/api/login/user_api.dart';
import 'package:yh_core_flutter_project/project/common/extension/api_service.dart';
import 'package:yh_core_flutter_project/project/router/app_routers.dart';

import 'package:app_core/app_core.dart';

import '../../../common/intl/index.dart';
import '../../common/webview/pages/yh_webview_page.dart';
import '../../common/test/channel_test_page.dart';

class LoginLogic extends GetxController {
  final isEmailLogin = true.obs;

  final accountController = TextEditingController();
  final accountFocusNode = FocusNode();

  final codeController = TextEditingController();
  final codeFocusNode = FocusNode();

  final agree = false.obs;

  /// 验证码倒计时 - 使用响应式变量
  final countdownSeconds = 0.obs;

  final logoTapCount = 0.obs;
  DateTime? _lastTapTime;

  String get codeButtonText => countdownSeconds.value > 0 ? '${countdownSeconds.value}s' : '获取验证码';

  final canSendCode = false.obs;
  final canSubmit = false.obs;

  @override
  Future<void> onInit() async {
    super.onInit();
    accountController.addListener(_updateButtonStates);
    codeController.addListener(_updateButtonStates);

    _updateButtonStates();
    // print(EnvManager.appBaseUrl);
    // print(await AppPackageInfo.appName);
    //
    // print(EnvManager.currentEnv);
    // print(appGlobalConfig.netWorkConfig.baseUrl);

    getCommonVersion();
    print('LoginLogic控制器创建');

  }

  @override
  void onReady() {
    super.onReady();
    print('LoginLogic页面首次可见');
  }

  void _updateButtonStates() {
    canSendCode.value = countdownSeconds.value == 0 && accountController.text.isNotEmpty;
    canSubmit.value = accountController.text.isNotEmpty && codeController.text.isNotEmpty && agree.value;
  }

  void getCommonVersion() async {
    final result = await UserApi.commonVersion.request<VersionModel>(
      params: {"model": "18", "platform": "ios", "brandName": "ALL"},
      fromJson: VersionModel.fromJson,
    );
    YHLog.i(result.isSuccess);
    VersionModel? versionModel = result.data;
    YHLog.i(versionModel?.toJson());
    YHLog.i(versionModel);
    YHLog.i(result.message);
  }


  @override
  void onClose() {
    accountController.removeListener(_updateButtonStates);
    codeController.removeListener(_updateButtonStates);
    accountController.dispose();
    codeController.dispose();
    super.onClose();
  }

  void switchToEmail() {
    isEmailLogin.value = true;
    accountController.clear();
    codeController.clear();
    _updateButtonStates();
  }

  void switchToPhone() {
    isEmailLogin.value = false;
    accountController.clear();
    codeController.clear();
    _updateButtonStates();
  }

  /// 发送验证码
  void sendVerificationCode() async {
    if (!canSendCode.value) return;
    String account = accountController.text.trim();
    if (isEmailLogin.value) {
      if (!Validator.isEmail(account)) {
        YHSmartDialog.showMsg('请输入正确的邮箱地址');
        return;
      }
    } else {
      if (!Validator.isChinesePhone(account)) {
        YHSmartDialog.showMsg('请输入正确的手机号码');
        return;
      }
    }

    final result = await UserApi.codeSend.request(
      params: {"business": "login", "tenantId": "20", "target": "+86${accountController.text}"},
      config: RequestConfig(baseUrl: _buildUimBaseUrl()),
    );
    if (result.isSuccess) YHSmartDialog.showMsg('验证码发送成功');
    // YHLog.i(result.raw);
    // YHLog.i(result.data);
    // YHLog.i(result.isSuccess);
  }

  /// 需要走 uim 的接口
  String _buildUimBaseUrl() {
    String uimBaseUrl = 'http://192.168.167.28:8888';
    final envBase = EnvManager.appBaseUrl;
    var base = envBase;
    if (EnvManager.currentEnv == EnvType.dev) {
      base = uimBaseUrl;
    } else {
      base = '$base/uim';
    }
    if (base.contains('/app')) base = base.replaceFirst('/app', '');
    return base;
  }

  /// 开始倒计时
  void startCountdown() {
    countdownSeconds.value = 60;

    Timer.periodic(Duration(seconds: 1), (timer) {
      if (countdownSeconds.value > 0) {
        countdownSeconds.value--;
        _updateButtonStates();
      } else {
        timer.cancel();
        _updateButtonStates();
      }
    });
  }

  ///登录
  void login() async {
    String account = accountController.text.trim();
    String code = codeController.text.trim();
    int platform;
    if (defaultTargetPlatform == TargetPlatform.iOS) {
      platform = 0;
    } else if (defaultTargetPlatform == TargetPlatform.android) {
      platform = 1;
    } else {
      platform = 5;
    }
    final result = await UserApi.login.request<UserModel>(
      params: {"account": "+86$account", "tenantId": 20, "platform": platform, "code": code},
      config: RequestConfig(baseUrl: _buildUimBaseUrl()),
      fromJson: UserModel.fromJson,
    );
    if(result.isSuccess){
      userManager.loginSave(result.data);
      Get.offAllNamed(AppRouters.mainTab.name);
    }
  }

  void register(String code) async {
    var account = accountController.text;
    final res = await UserApi.register.request(params: {"email": account, "code": code, "country": "CN"}, showLoading: true);
    if (res.isSuccess) {
      YHSmartDialog.showMsg("注册成功");
      Get.until((route) => Get.currentRoute == AppRouters.login.r);

      /// 返回到登录页面
    } else {
      YHSmartDialog.showMsg(res.message ?? "注册失败");
    }
  }

  void toggleAgree() {
    agree.value = !agree.value;
    _updateButtonStates();
  }

  void openPrivacyPolicy() {
    Get.log("打开隐私政策");
    Get.to(() => ChannelTestPage());
    // Get.to(() => YHWebViewPage(
    //   // initialUrl: 'https://example.com/privacy',
    //   title: '隐私政策',
    // ));
  }

  void openTermsOfService() {
    Get.log("打开服务条款");
    // Get.toNamed(AppRouters.webView.r);
    ///用构造函数参数
    Get.to(
      () => YHWebViewPage(
        // initialUrl: 'https://www.baidu.com/?tn=15007414_20_dg',
        title: '服务条款',
      ),
    );
  }

  /// Logo连击处理
  void onLogoTap() {
    if (!appGlobalConfig.appConfig.isDebug) {
      YHLog.i('生产环境环境切换入口关闭');
      return;
    }

    DateTime now = DateTime.now();
    if (_lastTapTime == null || now.difference(_lastTapTime!).inSeconds > 3) {
      logoTapCount.value = 0;
      _lastTapTime = now;
    }

    logoTapCount.value++;
    YHLog.i('Logo点击次数: ${logoTapCount.value}');

    if (logoTapCount.value >= 5) {
      YHLog.i('Logo连击达到5次，跳转到调试页面');
      navigateToDebug();
    }
  }

  void navigateToTest() {
    Get.toNamed(AppRouters.baseTest.r);
  }

  void navigateToSignUp() {
    Get.toNamed(AppRouters.signUp.r);
  }

  void navigateToDebug() {
    Get.toNamed(AppRouters.debug.r);
  }
}
